import { defineStore } from "pinia";
import { store } from "@/store";
import type { TableHeaderRule, HmiMenu } from "@/api/hmi/config.api";
import HmiConfigAPI from "@/api/hmi/config.api";
import { computed } from "vue";

/**
 * HMI 配置 Store
 */
export const useHmiConfigStore = defineStore("hmiconfig", () => {
  // 存储 hmi 配置规则数据
  // const hmiconfig = useStorage<TableHeaderRule[]>("hmiconfig", []);
  // hmiconfig 不使用缓存
  const hmiconfig = ref<TableHeaderRule[]>([]);
  // hmiHasInited 是否初始化
  const hmiHasInited = computed(() => {
    return hmiconfig.value.length > 0;
  });

  /**
   * 初始化 hmi 配置规则数据
   */
  function initHmiConfig() {
    if (hmiHasInited.value) return;

    return new Promise<void>((resolve, reject) => {
      HmiConfigAPI.getHmiConfig()
        .then((res) => {
          // console.log("initHmiConfig", res);
          Object.assign(hmiconfig.value, res.hmiconfig);
          resolve();
        })
        .catch((error) => {
          reject("initHmiConfig 获取 hmi 配置规则数据失败:" + error);
        });
    });
  }

  /**
   * 根据 uri 查询对应的配置规则，支持 rule.uri 中的 {cpu}、{zone} 等数字占位符
   * @param uri 路径
   * @returns TableHeaderRule | undefined
   */
  const getTableHeaderRuleByUri = (uri: string): TableHeaderRule | null => {
    if (!hmiHasInited.value) {
      console.error("hmi 配置规则数据未初始化");
      return null;
    }
    for (const rule of hmiconfig.value) {
      const uris = Array.isArray(rule.uri) ? rule.uri : [rule.uri];
      for (const ruleUri of uris) {
        if (!ruleUri) continue;
        // 将 {xxx} 替换为 \\d+，构造正则
        const pattern = "^" + ruleUri.replace(/\{[a-zA-Z]+\}/g, "\\d+") + "$";
        const regex = new RegExp(pattern);
        if (regex.test(uri)) {
          return rule;
        }
      }
    }
    return null;
  };

  /**
   * 根据 path 查询对应的规则配置，
   * @param path 路径
   * @returns TableHeaderRule | undefined
   */
  const getTableHeaderRuleByPath = (path: string): TableHeaderRule | null => {
    if (!hmiHasInited.value) {
      console.error("hmi 配置规则数据未初始化");
      return null;
    }
    /** path = "/event/audit-cpu-1" 只保留 audit-cpu-1 */
    const path_last = path.split("/").slice(-1)[0];
    for (const rule of hmiconfig.value) {
      const paths = Array.isArray(rule.path) ? rule.path : [rule.path];
      for (const rulePath of paths) {
        if (rulePath === path_last) {
          return rule;
        }
      }
    }
    return null;
  };

  /**
   * 获取 hmi 菜单定义
   * @returns Promise<HmiMenu[]>
   */
  function getHmiMenu() {
    return new Promise<HmiMenu[]>((resolve, reject) => {
      HmiConfigAPI.getHmiMenuConfig()
        .then((res) => {
          resolve(res.data.data.hmimenu);
        })
        .catch((error) => {
          reject("getHmiMenu 获取 hmi 菜单定义失败:" + error);
        });
    });
  }

  return {
    hmiconfig,
    hmiHasInited,
    initHmiConfig,
    getTableHeaderRuleByUri,
    getTableHeaderRuleByPath,
    getHmiMenu,
  };
});

/**
 * 适用于 setup 之外的场景
 */
export function useHmiConfigStoreHook() {
  return useHmiConfigStore(store);
}
